<template>

  <el-tabs type="border-card" @tab-remove="removeTab" :closable="true">
    <el-tab-pane :label="titleName">
      <el-container>

        <el-main>
          <cwBaseInfo :baseInfo="baseinfo">
            <template #finance1>

              <el-row>
                <el-col :span="8">
                  <el-form-item :label="limitName">
                    <el-input v-model="finance.summary.limit" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="已申金额">
                    <el-input v-model="finance.summary.yi" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="未申金额">
                    <el-input v-model="finance.summary.wei" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item :label="finance.type_name + '名称'" v-if="finance.paytype != 1">
                <el-input v-model="finance.title"
                          :disabled="finance.disabled"
                          v-if="finance.paytype != 4">
                </el-input>
                <el-input v-else v-model="finance.title" disabled></el-input>
              </el-form-item>
              <el-form-item :label="finance.type_name + '金额'" v-if="finance.paytype != 1">
                <el-input
                  v-model="finance.money"
                  :disabled="finance.disabled"
                  @blur="$fmoney"
                  v-if="finance.paytype != 4"
                >
                </el-input>
                <el-input v-else v-model="finance.money" :disabled="finance.disabled" @blur="$fmoney">
                </el-input>
              </el-form-item>


              <el-form-item label="差旅详情" v-if="finance.paytype == 1">
                <el-table
                  :data="finance.clv_list"
                  tooltip-effect="dark"
                  style="width: 100%;"
                  :summary-method="getSummaries"
                  show-summary
                >

                  <el-table-column label="名称" width="150px">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.name"
                        size="mini"
                        :disabled="scope.row.disabled"
                      >

                      </el-input>
                    </template>
                  </el-table-column>

                  <el-table-column label="出差日期" align="center">
                    <template slot-scope="scope">
                      <el-date-picker
                        size="small"
                        v-model="scope.row.date"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        @blur="getClvCost(scope)"
                        value-format="yyyy-MM-dd"
                        :disabled="scope.row.disabled"
                        :picker-options="{ disabledDate: disabledDate }"
                        style="width: 220px"
                      >
                      </el-date-picker>
                    </template>
                  </el-table-column>

                  <el-table-column label="差旅人员">
                    <template slot-scope="scope">
                      <el-tag
                        :key="i"
                        v-for="(item,i) in scope.row.staff_list"
                        :closable="!scope.row.disabled"
                        :disable-transitions="false"
                        @close="handleClose(item,scope)">
                        {{ item }}
                      </el-tag>

                      <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @blur="handleInputConfirm(scope)"
                      >
                      </el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showInput(scope)"
                        :disabled="scope.row.disabled"
                      >添加</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column label="性别" width="100px">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.sex" placeholder="请选择" size="mini" @change="getClvCost(scope)"
                                 :disabled="scope.row.disabled">
                        <el-option :value="1" label="男"></el-option>
                        <el-option :value="2" label="女"></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="城市等级" width="120px">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.city_level" size="mini" placeholder="请选择"
                                 @change="getClvCost(scope)" :disabled="scope.row.disabled">
                        <el-option
                          v-for="item in city_list"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="出差天数" width="80px">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.day" size="mini" disabled></el-input>
                    </template>
                  </el-table-column>

                  <el-table-column label="出差费用" width="120px">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.cost" size="mini" disabled></el-input>
                    </template>
                  </el-table-column>

                  <el-table-column label="出差城市" width="100px">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.city" size="mini" :disabled="scope.row.disabled"></el-input>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="80px">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        :disabled="scope.row.disabled"
                        type="danger"
                        @click="delClv(scope)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>

                  <div slot="append" style="text-align: center;margin: 10px;">
                    <el-button type="primary" @click="addClv(1)" :disabled="finance.disabled">添加差旅</el-button>
                  </div>

                </el-table>

              </el-form-item>

              <div v-if="finance.paytype == 5">
                <el-form-item label="客户名称">
                  <el-select v-model="finance.ticket_id" placeholder="请选择客户" size="medium" @change="getTicket"
                             style="width:500px;" :disabled="finance.disabled">
                    <el-option v-for="(ticket,t) in ticketList" :key="t" :label="ticket.name"
                               :value="ticket.id"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="税号">
                  <el-input v-model="ticketInfo.batch_id" disabled></el-input>
                </el-form-item>

                <el-form-item label="地址">
                  <el-input v-model="ticketInfo.address" disabled></el-input>
                </el-form-item>

                <el-form-item label="电话">
                  <el-input v-model="ticketInfo.mobile" disabled></el-input>
                </el-form-item>

                <el-form-item label="开户行">
                  <el-input v-model="ticketInfo.bank" disabled></el-input>
                </el-form-item>

                <el-form-item label="账号">
                  <el-input v-model="ticketInfo.account" disabled></el-input>
                </el-form-item>

                <el-form-item label="开户行号">
                  <el-input v-model="ticketInfo.bank_number" disabled></el-input>
                </el-form-item>

                <el-form-item label="发票类型">
                  <el-select v-model="finance.ticket_category" placeholder="请选择发票类型" size="medium"
                             style="width:500px;" value-key="id" :disabled="finance.disabled">
                    <el-option v-for="(cate) in ticketCategory" :key="cate.id" :label="cate.value"
                               :value="cate.id"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="申请类别">
                  <el-select v-model="finance.ticket_type" placeholder="请选择申请类别" size="medium"
                             style="width:500px;" value-key="id" :disabled="finance.disabled">
                    <el-option v-for="(type) in ticketType" :key="type.id" :label="type.value"
                               :value="type.id"></el-option>
                  </el-select>
                </el-form-item>
              </div>


              <!-- 附件列表-->
              <el-form-item label="附件" v-if="finance.is_upload_file">
                <MyUploadFile
                  dir="financial"
                  :files="finance.file_list"
                  ref="financeFile"
                >
                </MyUploadFile>
              </el-form-item>
              <!--        附件列表-->

              <el-form-item label="附件" v-else-if="file_ist.length > 0">
                <showFileList :fileList="file_ist"></showFileList>
              </el-form-item>


              <el-form-item label="备注">
                <el-input
                  type="textarea"
                  v-model="finance.desc"
                  maxlength="1500"
                  show-word-limit
                  :disabled="finance.disabled"
                ></el-input>
              </el-form-item>

              <!--      按钮-->
              <el-form-item v-if="finance.is_show_btn">
                <el-button type="primary" @click="editFinanceData(0)">{{ finance.btn }}</el-button>
                <el-button type="primary" @click="editFinanceData(1)">保存</el-button>
                <el-button type="primary">取消</el-button>
              </el-form-item>

              <!--回执单-->
              <el-form-item label="回执单" v-if="finance.show_hzd">
                <!-- 附件列表-->
                <MyUploadFile
                  dir="hzd"
                  :files="finance.hzd_list"
                  ref="hzdUpload"
                >
                </MyUploadFile>
              </el-form-item>

              <el-form-item label="回执单" v-else-if="hzd_list.length > 0">
                <showFileList :fileList="hzd_list"></showFileList>
              </el-form-item>

            </template>

          </cwBaseInfo>

        </el-main>

        <el-footer>

          <spForm :form="spform" v-if="finance.is_hidden" ref="spForm"></spForm>

          <history :history="history"></history>
        </el-footer>
      </el-container>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import {
  getFinanceDetail,
  editFinance,
  getClvFee,
  getTicketInfo,
  addFinanceHzd,
  delFinanceHzd,
  delClvAPI
} from '@/apilist/Finance'
import history from "../common/history";
import spForm from "../common/spForm";
import topNavbar from "../common/topNavbar";
import {mapState, mapActions} from 'vuex'
import cwBaseInfo from "./children/cwBaseInfo";
import uploadFile from "../common/uploadFile";
import showFileList from "../common/ShowFileList.vue";
import fileList from "../common/fileList.vue";
import MyUploadFile from "../common/MyUploadFile.vue";

export default {
  name: "financeDetail",
  data() {
    return {
      titleName: '',
      id: '',
      baseinfo: {},
      history: {},
      finance: {
        summary: {
          limit: '0.00',
          yi: '0.00',
          wei: '0.00',
        },
      },
      spform: {
        note: '',//审批备注
        newData: '',
        type: 'cw',
        fileList: [],
      },
      path: '/financial/list',
      title: '财务列表',
      city_list: [{id: 1, name: '一线'}, {id: 2, name: '二线'}, {id: 3, name: '三线'}, {id: 4, name: '四线'}],
      ticketList: [],
      ticketCategory: [],
      ticketType: [],
      ticketInfo: {},
      //inputVisible: false,
      //inputValue: '',
      file_ist: [],
      hzd_list: [],
      isSubmit: true,
    }
  },
  computed: {
    ...mapState("Setdata", ['user_all']),
    limitName() {
      return this.finance.type_name + '限额'
    }
  },
  components: {fileList, cwBaseInfo, history, spForm, topNavbar, uploadFile, showFileList, MyUploadFile},
  methods: {
    handleClose(tag, scope) {
      let row = scope.row
      let index = scope.$index
      let staffs = row.staff_list
      staffs.splice(staffs.indexOf(tag), 1)
      // 创建新对象保持独立性
      const newItem = {
        ...this.finance.clv_list[index], // 保留其他属性
        staff_list: staffs
      }
      // 使用 Vue.set 确保响应式
      this.$set(this.finance.clv_list, index, newItem)
      this.getClvCost(scope)
    },

    showInput(scope) {
      const row = scope.row
      const index = scope.$index

      // 创建新对象保持独立性
      const newItem = {
        ...this.finance.clv_list[index], // 保留其他属性
        inputVisible: true,
        inputValue: row.staff_list.includes(row.inputValue)
          ? row.inputValue
          : ''
      }

      // 使用 Vue.set 确保响应式
      this.$set(this.finance.clv_list, index, newItem)
    },

    handleInputConfirm(scope) {
      let row = scope.row
      let index = scope.$index
      let inputValue = row.inputValue;
      let staffs = row.staff_list
      if (inputValue) {
        staffs.push(inputValue);
      }
      const newItem = {
        ...this.finance.clv_list[index], // 保留其他属性
        inputVisible: false,
        inputValue: '',
        staff_list: staffs
      }

      // 使用 Vue.set 确保响应式
      this.$set(this.finance.clv_list, index, newItem)
      this.getClvCost(scope)

    },
    ...mapActions("Setdata", ['getAllRoleAndUserAction']),
    getSummaries(param) {
      const {columns, data} = param;
      let sum = 0;
      this.finance.clv_list.forEach((row, index) => {
        let is_del = row.is_del ||  0 ;
        //let is_del = row.hasOwnProperty('is_del') ? row.is_del : 0;
        if(!is_del){
          let cost = this.fun.resetMoney(row.cost)
          sum += cost
        }

      })

      sum = this.fun.fmoney(sum)
      this.spform.newData.money = sum
      return ['总计', '', '', sum, '']
    },

    addClv(isAdd) {
      let clv = {
        name: '',
        staff_list: [],
        date: [],
        day: '',
        city_level: 1,
        cost: 0,
        city: '',
        id: 0,
        sex: 1,
        disabled: false
      }
      this.finance.clv_list.push(clv)
    },
    //计算差旅费用
    getClvCost(scope) {
      const {$index: index, row} = scope
      let that = this;
      getClvFee(row).then(res => {
        that.finance.clv_list[index].day = res.data.day
        that.finance.clv_list[index].cost = res.data.cost
      })
    },

    async editFinanceData(is_save) {
      if (!this.isSubmit) return false;
      this.isSubmit = false;
      // 处理附件文件列表
      if (this.finance.is_upload_file && this.$refs.financeFile) {
        this.finance.file_list = this.$refs.financeFile.getNewFileList();
      } else {
        this.finance.file_list = [];
      }

      // 构造请求参数
      let params = {
        id: this.id,
        is_save: is_save,
        finance: {...this.finance},
        xmid: this.finance.xmid,
        type: this.finance.paytype
      };

      // 处理审批表单数据
      if (this.finance.is_hidden && this.$refs.spForm) {
        params.spForm = {
          note: this.$refs.spForm.form.note,
          fileList: this.$refs.spForm.getSPFilesComputed()
        }
      }

      // 处理回执单文件
      if (this.finance.show_hzd && this.$refs.hzdUpload) {
        params.finance.hzd_list = this.$refs.hzdUpload.getNewFileList();
      }

      console.log("editFinance: ", params);

      try {
        const res = await editFinance(params);
        await this.$success(res.msg);
        // 重新获取详情数据
        await this.getDetail();
        // 如果是保存操作，提示用户保存成功
      } catch (error) {
        Promise.reject(error)
      } finally {
        this.isSubmit = true;
      }
    },

    async getDetail() {
      const res = await getFinanceDetail({id: this.id});
      this.baseinfo = res.data.baseInfo;
      this.history = res.data.history;
      this.finance = res.data;
      this.finance.summary = res.data.summaryData;
      this.spform.newData = res.data;
      this.file_ist = res.data.file_list;
      this.hzd_list = res.data.hzd_list;
      if (res.data.hasOwnProperty('ticketList')) this.ticketList = res.data.ticketList
      if (res.data.hasOwnProperty('ticketCategory')) this.ticketCategory = res.data.ticketCategory
      if (res.data.hasOwnProperty('ticketType')) this.ticketType = res.data.ticketType
      if (res.data.hasOwnProperty('ticketInfo')) this.ticketInfo = res.data.ticketInfo
      this.spform.note = res.data.spForm.note;
      this.spform.fileList = res.data.spForm.fileList;
    },

    //获取发票
    getTicket() {
      getTicketInfo({id: this.finance.ticket_id}).then(res => {
        this.ticketInfo.batch_id = res.data.batch_id
        this.ticketInfo.address = res.data.address
        this.ticketInfo.mobile = res.data.mobile
        this.ticketInfo.bank = res.data.bank
        this.ticketInfo.account = res.data.account
        this.ticketInfo.bank_number = res.data.bank_number
      })
    },

    removeTab() {
      this.$router.push('/financial/list');
    },

    disabledDate(date) {
      // 获取当前日期
      const today = new Date();
      // 计算15天前的日期
      const fifteenDaysAgo = new Date();
      fifteenDaysAgo.setDate(today.getDate() - 15);

      // 禁用15天前的日期
      return date < fifteenDaysAgo;
    },
    //检查名称是否重复
    checkClvName(scope) {
      try {
        const {$index: index, row} = scope
        this.finance.clv_list.forEach((v, i) => {
          if (i != index && row['name'] == v['name']) {
            throw new Error(`差旅名称${row['name']}重复,请检查`)
          }
        });
      } catch (e) {
        this.$message.error(e.message)
      }
    },

    delClv(scope) {
      const {$index: index, row} = scope
      this.$confirm(`是否删除差旅${row['name']}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.hasOwnProperty('id') && row.id) {
          delClvAPI({id: row.id}).then(res => {
            //this.$message.success(res.message)
            this.$message(
              {
                type:"success",
                message: res.message,
                onClose: ()=>{
                  this.getDetail()
                }
              }
            )

          })
        }
        //this.finance.clv_list.splice(index, 1)
      }).catch(() => {
        this.$message.info('已取消删除');
      })

    }

  },
  async mounted() {
    this.id = this.$route.query.id;
    this.titleName = this.$route.query.title;
    await this.getDetail();
    await this.getAllRoleAndUserAction()
  }
}
</script>

<style scoped>

</style>
